import { ref } from 'vue'
import { defineStore } from 'pinia'
import router from '../router'
import type { IAuthUser, ITabPage } from "../types/system"
import type { TabPaneName } from "element-plus"

const store = defineStore(
  'mystore',
  () => {


    //token
    const token = ref<string>('')

    //user
    const user = ref<IAuthUser>({
      
      userName: '',
      imgPath: '',
      token: ''
    });
    var goodsCart=reactive([])
    //TabPages
    const menuactive = ref<string>('0');      //菜单选中
    const tabsvalue = ref<TabPaneName>('0');  //选项卡选中
    const tabslist = ref<ITabPage[]>([
      {
        name: '0',
        label: '工作台',
        url: '/system/workbench',
        icon: 'Monitor',
        disabled: false,
        closable: false,
        keep: false
      }
    ]);

    const addCart=(zhi)=>{
  if (goodsCart.some(v => v.gid == zhi.gid&&v.Pl==zhi.Pl)) {
        goodsCart.filter(v => v.gid == zhi.gid)[0].number++;
        alert('追加成功');
      } else {
        goodsCart.push(JSON.parse(JSON.stringify(zhi)));
        alert('添加成功');
      }


    }
const qk=()=>{

  goodsCart=[]
}
    const deleteCart=(zhi)=>{
       let index = goodsCart.findIndex(v=>v.gid==zhi.gid&&v.Pl==zhi.Pl);
        goodsCart.splice(index,1)


    }
    //添加新的选项卡
    const addTab = (tab: ITabPage) => {
      //判断是否已经包含该选项卡
      if (!tabslist.value.some(t => t.name == tab.name)) {
        tabslist.value.push(tab); //新增选项卡
      }
      //切换选项卡
      tabsvalue.value = tab.name;
      changeTab(tab.name)
    }
    //移除选项卡
    const removeTab = (tabName: TabPaneName) => {
      const tabs = tabslist.value;
      let activeName = tabsvalue.value;
      //判断移除的选项是否是激活选项
      if (activeName === tabName) {
        tabs.forEach((tab, index) => {
          if (tab.name === tabName) {
            const nextTab = tabs[index + 1] || tabs[index - 1];
            if (nextTab) {
              activeName = nextTab.name;
            }
          }
        })
      }
      //切换新的激活Tab
      tabsvalue.value = activeName;
      //移除Tab
      tabslist.value = tabs.filter((tab) => tab.name !== tabName);

      changeTab(activeName)
    }
    //选项卡切换  刷新数据
    const changeTab = (tabName: TabPaneName) => {
      //判断需要切换的Tab是否是当前菜单
      if (tabName != menuactive.value) {
        //设置菜单选中
        menuactive.value = tabName as string;
        let tab = tabslist.value.filter(f => f.name == tabName)[0];
        //跳转页面
        router.push({ path: tab.url });
      }
    }

    //导出
    return {
      user, token, menuactive,
      tabslist, tabsvalue, addTab, removeTab, changeTab,addCart,qk,deleteCart,goodsCart
    }
  }
  ,{
    persist: {
      enabled: true  // 开启数据缓存
      , strategies: [
        { storage: sessionStorage, paths: ["token", "user", 'menuactive', 'tabsvalue', 'tabslist',] },
      ]  //自定义存储
    }
  }
)

export default store 